//封装分类数据业务相关代码
import { getCategoryListAPI } from '@/api/index.js'
import { ref, onMounted } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'

export function useCategory() {
  const categoryList = ref({})
  const route = useRoute()
  const getCategoryList = async (id = route.params.id) => {
    const res = await getCategoryListAPI(id)
    categoryList.value = res.data.result
  }
  onMounted(() => getCategoryList())

  //目标：路由参数变化的时候，可以把分类数据接口重新发送
  onBeforeRouteUpdate((to) => {
    //存在问题：使用最新的路由参数请求最新的分类数据
    getCategoryList(to.params.id)
  })
  return {
    categoryList
  }
}